<?php

namespace Common\Model;
use Think\Model;

// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------


class UsersModel extends Model {

    /**
     * 用户登录
     * @author 462193409@qq.com
     */
    public function login($username, $password, $type = 1) {
        //去除前后空格
        $username = trim($username);
        if(empty($username)){
            $a['info'] = "手机或者邮箱不能为空！";
            $a['status'] = FALSE;
            echo json_encode($a);
        }
        if ($password == 0) {
            $map['user_mobile'] = array('eq', $username); //邮箱登陆
        }else{
            $map['user_email'] = array('eq', $username); //用户名登陆
        }
        if ($type != 1) {
            $map['user_group_id'] = array('eq', $type);
        }

        $user = $this->where($map)->find(); //查找用户
        if (!$user) {
            $a['info'] = "账户不存在，请注册后再试！";
            $a['status'] = FALSE;
            $a['url'] = U('Register/mobile');
            echo json_encode($a);
        }else{
            if ($user['user_state'] == 1) {
                if($password !=0){
                    list($passwords, $salt) = password($password, $user['user_salt']);
                    if ($passwords != $user['user_passwd']) {
                        $a['info'] = "密码不正确！";
                        $a['status'] = FALSE;
                        echo json_encode($a);
                    }
                }
                //更新登录信息
                $data = array(
                    'user_id' => $user['user_id'],
                    'user_login_num' => array('exp', '`user_login_num`+1'),
                    'user_login_time' => time(),
                    'user_login_ip' => get_client_ip(1),
                );
                $this->save($data);
                $this->autoLogin($user);
                return $user['user_id'];
            } else {
                $a['info'] = "账户异常，请联系客服！";
                $a['status'] = FALSE;
                $a['url'] = U('Index/index');
                echo json_encode($a);
            }
        }
    }

    /**
     * 设置登录状态
     * @author 462193409@qq.com
     */
    public function autoLogin($user) {
        //记录用户的信息
        session('user_id', $user['user_id']);
        session('user_name', $user['user_name']);
        //记录商户的信息
        if($user['user_group_id'] == 2){
            session('store_id', $user['user_store_id']);
            $map['store_id'] = $user['user_store_id'];
            $auth = M('store')->where($map)->find();
            session('store_name',$auth['store_name']);
        }
    }
}
